export default {
  namespaced: true,
  state() {
    return {
      cartList: JSON.parse(uni.getStorageSync('cart') || '[]')
    }
  },
  mutations: {
    // 存储购物车最新数据
    setCartList(state, payload) {
      const resultCart = state.cartList.find(item => item.goods_id === payload.goods_id)
      if (!resultCart) {
        state.cartList.push(payload)
      } else {
        resultCart.goods_count ++ 
      }
    },
    // 修改复选框状态
    updateGoodsState(state, payload) {
      const stateResult = state.cartList.find(item => item.goods_id === payload.goods_id)
      if(stateResult) {
        stateResult.goods_state = payload.goods_state
      }
    },
    // 购物车商品数据持久化
    updateGoodsCount(state, payload) {
      const countResult = state.cartList.find(item => item.goods_id === payload.goods_id)
      if(countResult) {
        countResult.goods_count = payload.goods_count
      }
    },
    // 删除购物车选项
    removeGoodsCart(state, payload) {
      state.cartList = state.cartList.filter(item => item.goods_id !== payload.goods_id)
    },
    // 数据本地持久化
    savetoStoreage(state) {
      uni.setStorageSync('cart',JSON.stringify(state.cartList))
    },
    
    // 购物车全选反选
    checkAllCart(state,payload) {
      state.cartList.forEach(item => {
        item.goods_state = payload
      })
    }
  },
  actions: {
    // 数据持久化
    savetoStoreage(ctx) {
      ctx.commit('savetoStoreage')
    },
    // 修改购物车商品选项复选框状态
    updateGoodsState(ctx, goodsState) {
      ctx.commit('updateGoodsState', goodsState)
      ctx.commit('savetoStoreage')
    },
    updateGoodsCount(ctx, goodsCount) {
      ctx.commit('updateGoodsCount', goodsCount)
      ctx.commit('savetoStoreage')
    },
    removeGoodsCart(ctx, goodsItem) {
      ctx.commit('removeGoodsCart', goodsItem)
      ctx.commit('savetoStoreage')
    },
    // 购物车全选反选
    checkAllCart(ctx, selected) {
      ctx.commit('checkAllCart', selected)
    }
  },
  getters: {
    // 计算商品数量
    total(state) {
      let c = 0
      state.cartList.forEach(item => c += item.goods_count)
      return c
    },
    // 选中的商品列表
    selectedList(state,getters) {
      return state.cartList.filter(item => item.goods_state)
    },
    
    //是否全选
    isCheckAll(state,getters) {
     return state.cartList.length === getters.selectedList.length && getters.selectedList.length !== 0
    },
    // 计算选中商品的总金额
    selectedAccount(state,getters) {
      return getters.selectedList.reduce((p, c) => p + Math.round(c.goods_price * 100) * c.goods_count, 0) / 100
    }
  }
}